package com.zhl.tzsb;

import org.junit.Test;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: demos
 * @description:
 * @author: 刘振华
 * @create: 2020-11-14 12:02
 **/
public class JspReader {
	int size = 200;
	Map<String,String> actionMapJsp = new HashMap<>(size);
	Map<String, Map<String,String>> jspMapTableColumnComments = new HashMap<>(size);
	@Test
	public void readJsp(){

		//action跟table名称对应
		Map<String,String> actionMapTable = getFile();

		String path = "D:\\work\\workspace\\demos\\web-demo\\tzsb\\index.txt";
		Map<String,String> indexActionMapTable = new HashMap<>(size);
		// 1.将action和grid页面对应起来
		FileReader fileReader = null;
		BufferedReader bfr = null;
		try {
			fileReader = new FileReader(new File(path));
			bfr = new BufferedReader(fileReader);
			String line = "";
			boolean flag = true;
			while ((line = bfr.readLine()) != null){
				line = line.trim();
				if(line.startsWith("<%--")){
					flag = false;
					continue;
				}
				if(line.endsWith("-->")){
					flag = true;
				}
				if(flag) {
					if (line.startsWith("<li><a href=\"${ctx}")) {
						//<li><a href="${ctx}/main/pipe/base/pipe-management!abc.action?moduletype=PP_PIPE" target="navTab" rel="module-pipe-management" title="压力管道基本信息管理">压力管道基本信息管理</a></li>
						String[] ans = line.split("\"");
						String[] anss = ans[1].split("/");
						String[] actionAndTable = anss[anss.length - 1].split("\\?");
						String s = actionAndTable[0].replace(".action","");
						if(s.contains("!")){
							s = s.split("!")[0];
						}
						String actionName = getBigName(s)+"Action";
						String tableName = "";
						if (actionAndTable.length > 1) {
							tableName = actionAndTable[1].split("=")[1];
						}
						String[] comts = line.replace("</a></li>","").split(">");
						String tableComment = comts[comts.length-1];
						String jspName = s + "-grid.jsp";

//						System.out.println(actionName + ":" + tableComment + ":" + jspName + ":" + tableName);
//						System.out.println(tableComment + ":"+ tableName);
						if(tableName.equals("")){
							tableName = actionMapTable.get(actionName);
						}
						indexActionMapTable.put(actionName,tableComment+","+tableName);
						actionMapJsp.put(actionName,jspName);
					}
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}finally {
			if(null != fileReader) {
				try {
					fileReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(null != bfr) {
				try {
					bfr.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		// 2.根据url找到jsp页面，解析每个字段
		String jspPath = "D:\\work\\workspace\\tlm\\tzsb\\web\\WEB-INF\\content\\main";
		findJsp(new File(jspPath));


//		System.out.println(indexActionMapTable.size());
//		System.out.println(jspMapTableColumnComments.size());
//		System.out.println(actionMapJsp.size());
//		System.out.println(actionMapTable.size());
		indexActionMapTable.forEach((k,v)->{
			System.out.println(k+","+v);
		});
		System.out.println("===========================");
		actionMapJsp.forEach((k,v)->{
			System.out.println(k+","+v);
		});

//		for(String key:indexActionMapTable.keySet()){
//			String tableName = indexActionMapTable.get(key);
//			String jspName = actionMapJsp.get(key);
//			Map<String, String> columnComments = jspMapTableColumnComments.get(jspName);
//			if(columnComments == null ){
//				continue;
//			}
//			String csvName = "D:\\work\\workspace\\demos\\web-demo\\tzsb\\index\\"+tableName.split(",")[0]+".csv";
//			File file = new File(csvName);
//			file.delete();
//			FileWriter fw = null;
//			BufferedWriter cbfr = null;
//			try {
//				file.createNewFile();
//				fw = new FileWriter(file);
//				cbfr = new BufferedWriter(fw);
//				cbfr.write(tableName);
//				cbfr.newLine();
//				for(String ckey:columnComments.keySet()){
//					cbfr.write(ckey.toUpperCase()+","+columnComments.get(ckey));
//					cbfr.newLine();
//				}
//			}catch (Exception e){
//				e.printStackTrace();
//			}finally {
//				if(null != cbfr) {
//					try {
//						cbfr.close();
//					} catch (IOException e) {
//						e.printStackTrace();
//					}
//				}
//				if(null != fw) {
//					try {
//						fw.close();
//					} catch (IOException e) {
//						e.printStackTrace();
//					}
//				}
//
//			}
//		}
	}

	private void findJsp(File file){
		if(file.isDirectory()){
			File[] files = file.listFiles();
			for(int i = 0;i<files.length;i++){
				findJsp(files[i]);
			}
		}else{
			String name = file.getName();
			if(actionMapJsp.containsValue(name)){
				Map<String,String> commentMap = new HashMap<>(50);
				jspMapTableColumnComments.put(name,commentMap);
				//开始解析该jsp文件
				FileReader fr = null;
				BufferedReader bfr = null;
				try{
					fr = new FileReader(file);
					bfr = new BufferedReader(fr);
					String line = "";
					while ((line = bfr.readLine())!=null){
						line = line.trim();
						if(line.startsWith("<th ")){
							//<th width="100" field="workshopname" sortable="true" sortName="o.orgname">车间名称</th>
							String colName = line.split("\"")[3];
							String[] strs = line.replace("</th>", "").split(">");
							String comment = strs[strs.length-1];
							commentMap.put(colName,comment);
						}
					}
				}catch (Exception e){
					e.printStackTrace();
				}finally {
					if(null != fr) {
						try {
							fr.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					if(null != bfr) {
						try {
							bfr.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
	}


	@Test
	public void actionMap(){
		//action跟table名称对应
		Map<String,String> actionMapTable = getFile();
		// 2.根据url找到jsp页面，解析每个字段
		String jspPath = "D:\\work\\workspace\\tlm\\tzsb\\web\\WEB-INF\\content\\main";
		findJspAction(new File(jspPath),actionMapTable);


		for(String key:jspMapTableColumnComments.keySet()){
			String tableName = key;
			Map<String, String> columnComments = jspMapTableColumnComments.get(key);
			if(columnComments == null ){
				continue;
			}
			String csvName = "D:\\work\\workspace\\demos\\web-demo\\tzsb\\action\\"+tableName+".csv";
			File file = new File(csvName);
			file.delete();
			FileWriter fw = null;
			BufferedWriter cbfr = null;
			try {
				file.createNewFile();
				fw = new FileWriter(file);
				cbfr = new BufferedWriter(fw);
				cbfr.write(tableName);
				cbfr.newLine();
				for(String ckey:columnComments.keySet()){
					cbfr.write(ckey.toUpperCase()+","+columnComments.get(ckey));
					cbfr.newLine();
				}
			}catch (Exception e){
				e.printStackTrace();
			}finally {
				if(null != cbfr) {
					try {
						cbfr.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if(null != fw) {
					try {
						fw.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}

			}
		}
	}

	private void findJspAction(File file,Map<String,String> actionMapTable){
		if(file.isDirectory()){
			File[] files = file.listFiles();
			for(int i = 0;i<files.length;i++){
				findJspAction(files[i],actionMapTable);
			}
		}else{
			String name = file.getName();
			if(name.endsWith("-grid.jsp")){
				name = getBigName(name.replace("-grid.jsp",""))+"Action";
			}
			if(actionMapTable.containsKey(name)){
				Map<String,String> commentMap = new HashMap<>(50);
				jspMapTableColumnComments.put(actionMapTable.get(name),commentMap);
				//开始解析该jsp文件
				FileReader fr = null;
				BufferedReader bfr = null;
				try{
					fr = new FileReader(file);
					bfr = new BufferedReader(fr);
					String line = "";
					while ((line = bfr.readLine())!=null){
						line = line.trim();
						if(line.startsWith("<th ")){
							//<th width="100" field="workshopname" sortable="true" sortName="o.orgname">车间名称</th>
							String colName = line.split("\"")[3];
							String[] strs = line.replace("</th>", "").split(">");
							String comment = strs[strs.length-1];
							commentMap.put(colName,comment);
						}
					}
				}catch (Exception e){
					e.printStackTrace();
				}finally {
					if(null != fr) {
						try {
							fr.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					if(null != bfr) {
						try {
							bfr.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
	}

	public String getBigName(String nameBefore){
		String key = (char)(nameBefore.charAt(0)-32)+"";
		for(int i = 1;i<nameBefore.length();i++){
			char c = nameBefore.charAt(i);
			if((c+"").equals("-")){
				c = (char)(nameBefore.charAt(++i)-32);
			}
			key += c;
		}
		return key;
	}

	@Test
	public void testName(){
		System.out.println(getBigName("aa-bb-cc-dd"));
	}

//	@Test
	public Map<String,String> getFile(){
		// 0，循环读取action，将action名与表名对应
		Map<String,String> actionMapTable = new HashMap<>(200);
		String mainPath = "D:\\work\\workspace\\tlm\\tzsb\\src\\com\\creatsoft\\main";
		// 递归查找action和对应的entity
		File mainPathFile = new File(mainPath);
		File[] files = mainPathFile.listFiles();

		String actionSplit1 = " extends BasePageAction<";
		String tableFlag = "@Table";
		for (int i = 0; i < files.length; i++) {
			String webPath = files[i].getAbsolutePath()+File.separator+"web";
			String entityPath = files[i].getAbsolutePath()+File.separator+"entity";
			File[] actionFiles = new File(webPath).listFiles();
			for(int j = 0;j<actionFiles.length;j++){
				FileReader fr =null;
				BufferedReader bfr = null;
				try {
					fr = new FileReader(actionFiles[j]);
					bfr = new BufferedReader(fr);
					String line = "";
					while ((line = bfr.readLine())!= null){
						if(!line.contains(actionSplit1)){
							continue;
						}
						String[] strs = line.split(actionSplit1);
///*     */ public class BoilerAccidentAbnormalAction extends BasePageAction<BoilerAccidentAbnormal> {
						String actionName = strs[0]
							.replace("/*    */ public class ","")
							.replace("/*     */ public class ","");
						String entityName = strs[1].split(">")[0]+".java";
						//接下来去entity路径中找entity
						File file = new File(entityPath + File.separator + entityName);
						String tableName = "";
						if(file.exists()){
							///*      */ @Table(name = "BR_BOILER")
							FileReader efr = null;
							BufferedReader ebfr = null;
							try {
								efr = new FileReader(file);
								ebfr = new BufferedReader(efr);
								String eline = "";
								while ((eline = ebfr.readLine())!= null){
									if(eline.contains(tableFlag)){
										tableName = eline.trim().split("\"")[1];
										break;
									}
								}
							}catch (Exception e){
								e.printStackTrace();
							}finally {
								if(null!=efr){
									try {
										efr.close();
									} catch (IOException e) {
										e.printStackTrace();
									}
								}
								if(null!=ebfr){
									try {
										ebfr.close();
									} catch (IOException e) {
										e.printStackTrace();
									}
								}
							}
						}
						actionMapTable.put(actionName,tableName);
						break;
					}
				}catch (Exception e){
					e.printStackTrace();
				}finally {
					if(null!=fr){
						try {
							fr.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					if(null!=bfr){
						try {
							bfr.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		actionMapTable.put("HseManagementAction","PP_PIPE");
		actionMapTable.remove("/*      */");
//		actionMapTable.forEach((k,v)->{
//			System.out.println(k+":"+v);
//		});
		return actionMapTable;
	}

	public String readToString(String fileName) {
		String encoding = "UTF-8";
		File file = new File(fileName);
		Long filelength = file.length();
		byte[] filecontent = new byte[filelength.intValue()];
		try {
			FileInputStream in = new FileInputStream(file);
			in.read(filecontent);
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			return new String(filecontent, encoding);
		} catch (UnsupportedEncodingException e) {
			System.err.println("The OS does not support " + encoding);
			e.printStackTrace();
			return null;
		}
	}
}
